package cn.serein.charging.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

    // 创建单例模式
    public static  ObjectMapper mapper = new ObjectMapper();

    // 定义一个方法去实现将对象转化为字符串
    public static String toJson(Object object) {

        // 由于不需要每次都创建新的对象，浪费性能和资源
        // 使用单例模式
        // ObjectMapper mapper = new ObjectMapper();
        // return "";
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            throw  new RuntimeException(e);
        }

    }

    public static <T> T  fromJson(String json, Class<T> clazz) {

        try {
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }
}
